"""TODO: header"""

import os
import urllib

from google.appengine.ext import blobstore
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.ext.webapp import template


class ManagePage(webapp.RequestHandler):
  def get(self):
    submissions = db.GqlQuery(
        "SELECT * "
        "FROM Submission "
        "ORDER BY date ")
    blob_infos = blobstore.BlobInfo.get(
        [submission.content_blobstore_key for submission in submissions])
    submission_models = [
        SubmissionManagementModel(submission, blob_info)
        for (submission, blob_info) in zip(submissions, blob_infos)]

    path = os.path.join(os.path.dirname(__file__), 'manage_page.html')
    template_values = {
      'submission_models': submission_models,
    }
    self.response.out.write(template.render(path, template_values))


class DownloadPage(blobstore_handlers.BlobstoreDownloadHandler):
  def get(self, blobstore_key):
    blobstore_key = str(urllib.unquote(blobstore_key))
    blob_info = blobstore.BlobInfo.get(blobstore_key)
    # Send the download as a MIME file attachment per the BlobInfo.
    self.send_blob(blob_info, save_as=True)


class SubmissionManagementModel(object):
  """A model for displaying submissions on the manage page."""

  def __init__(self, submission, blob_info):
    """Constructor combining information from a Submission and a BlobInfo.

    Args:
      submission: the submit.model.Submission datastore object
      blob_info: the BlobInfo for the submission's uploaded file
    """
    self.email = submission.email
    self.date = submission.date
    self.content_blobstore_key = submission.content_blobstore_key
    self.filename = blob_info.filename
    self.filesize = blob_info.size

